from src.main.dao.BaseDao import BaseDao

class UserDao(BaseDao):

    def insert(self, username, password):
        query = "INSERT INTO bk_user (user_name, password) VALUES (%s, %s)"
        values = (username, password)
        return self.execute_sql(query, values)

    def update(self):
        query = "UPDATE bk_user SET username = %s, password = %s, nick_name = %s, email = %s, phone = %s, avatar_path = %s WHERE id = %s"
        values = (self.name, self.password, self.nickname, self.email, self.phone, self.avatarPath,self.id)
        return self.execute_sql(query, values)

    def saveOrUpdate(self,user):
        values = {
            'user_name': user.username,
            'password': user.password,
            'nick_name': user.nickname,
            'email': user.email,
            'phone': user.phone,
            'avatar_path': user.avatarPath,
        }

        if user.id:  # 如果对象具有ID，则尝试执行更新操作
            query = "UPDATE bk_user SET user_name = %(user_name)s, password = %(password)s, nick_name = %(nick_name)s, email = %(email)s, phone = %(phone)s, avatar_path = %(avatar_path)s WHERE id = %(id)s"
            values['id'] = user.id
        else:  # 如果对象没有ID，则执行插入操作
            query = "INSERT INTO bk_user (user_name, password, nick_name, email, phone, avatar_path) VALUES (%(user_name)s, %(password)s, %(nick_name)s, %(email)s, %(phone)s, %(avatar_path)s)"
        print(query)
        return self.execute_sql(query, values)

    def delete(self, user_id):
        query = "DELETE FROM bk_user WHERE id = %s"
        values = (user_id,)
        return self.execute_sql(query, values)

    def get_all_users(self):
        query = "SELECT id,user_name,password,nick_name,email,phone,avatar_path FROM bk_user"
        return self.execute_query(query)

    def get_user_by_id(self, user_id):
        query = "SELECT id,user_name,password,nick_name,email,phone,avatar_path FROM bk_user WHERE id = %s"
        values = (user_id,)
        return self.execute_query(query, values)

    def get_user_by_username(self, user_name):
        query = "SELECT id,user_name,password,nick_name,email,phone,avatar_path FROM bk_user WHERE user_name = %s"
        values = (user_name,)
        return self.execute_query(query, values)

    def get_user_info_by_page(self, page_number, page_size, filter_keyword):
        query = "SELECT id,user_name,password,nick_name,email,phone,avatar_path FROM bk_user where 1=1"

        # 添加关键词筛选条件
        if filter_keyword:
            query += " AND (user_name LIKE '%{}%' OR nick_name LIKE '%{}%')".format(filter_keyword, filter_keyword)

        # 添加分页条件
        query += " LIMIT {} OFFSET {}".format(page_size, (page_number - 1) * page_size)

        return self.execute_query(query)

